/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { message } from 'antd';
import {
  getAccounts,
  addAccount,
  updateAccount,
  deleteAccount,
  assignRole,
  switchStatus,
} from '@/services/account';
import {
  zyGetCompaniesList, // 中邮获取公司列表
  zyGetAcountsList, // 中邮获取账号列表
  zySwitchStatus, // 中邮，删除及修改账号账号权限
  zySave, // 中邮，添加及编辑账号
  zyPrivilegeSet, // 中邮，账号权限分配
  zyAddBranch,
  zyEditBranch, // 中邮，添加支局
} from '@/services/zyAcount';
import { isLegalData } from '@/utils/utils';

export default {
  namespace: 'accounts',

  state: {
    data: {},
    companiesTreeList: [], // 中邮公司账号树组件数据
    companiesCascaderList: [], // 中邮级联组件数据
    zyAcountsList: [], // 中邮账号列表数据
    zySelectedArray: [], // 中邮，选中的公司账号，包含父节点的数组
  },

  effects: {
    *updateList({ payload }, { put, select }) {
      const { id, ...rest } = payload;
      const { data } = yield select(_ => _.accounts);
      const newList = [...data.list];
      id.forEach(item => {
        const index = newList.findIndex(iitem => iitem.id === item);
        newList.splice(index, 1, {
          ...newList[index],
          ...rest,
        });
      });
      yield put({
        type: 'save',
        payload: {
          data: {
            ...data,
            list: newList,
          },
        },
      });
    },
    *getList({ payload }, { put, call }) {
      const response = yield call(getAccounts, payload);
      if (!response) return;
      const { code, data } = response;
      const { result } = data;
      if (code == 0 && data) {
        yield put({
          type: 'save',
          payload: {
            data: {
              list: result,
              pagination: false,
            },
          },
        });
      }
    },
    *add({ payload, then = () => {} }, { call, put }) {
      const response = yield call(addAccount, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        const { id } = payload;
        if (id) {
          yield put({
            type: 'updateList',
            payload: {
              ...payload,
              id: [id],
            },
          });
          message.success('修改成功');
        } else {
          message.success('添加成功');
        }
        then();
      } else {
        message.error(msg);
      }
    },
    *update({ payload, then }, { call }) {
      const response = yield call(updateAccount, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success(msg);
        then();
      } else {
        message.error(msg);
      }
    },
    *delete({ payload, then = () => {} }, { call }) {
      const response = yield call(deleteAccount, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success('删除成功');
        then();
      } else {
        message.error(msg);
      }
    },
    *assign({ payload, then = () => {} }, { call, put }) {
      const { id, privilege } = payload;
      if (id.length === 0) {
        message.error('请勾选可分配角色的条目');
        return;
      }
      const privileges = [];
      const privilegeName = [];
      if (privilege) {
        privilege.forEach(item => {
          privileges.push(item.type);
          privilegeName.push(item.key);
        });
      }
      const response = yield call(assignRole, {
        privilege: privileges.join(','),
        id,
      });
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success('分配成功');
        yield put({
          type: 'updateList',
          payload: {
            id,
            privilege: privilegeName.join(','),
          },
        });
        then();
      } else {
        message.error(msg);
      }
    },
    *switch({ payload, then = () => {} }, { call, put }) {
      const { is_forbiden, id } = payload;
      const statuses = ['开启', '禁用'];
      if (id.length === 0) {
        message.error(`请勾选可${statuses[is_forbiden]}条目`);
        return;
      }
      const response = yield call(switchStatus, {
        is_forbidden: is_forbiden,
        id,
      });
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success(`${statuses[is_forbiden]}成功`);
        yield put({
          type: 'updateList',
          payload: {
            id,
            is_forbiden,
          },
        });
        then();
      } else {
        message.error(msg);
      }
    },
    // 中邮获取左边公司数据
    *zyGetCompaniesList({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(zyGetCompaniesList, {
        id: payload.id,
        take_self: payload.take_self,
      });
      if (!response) return;
      const { code, data } = response;
      const treeList = [];
      treeList.push(...isLegalData(data, []));
      // level为4代表支局，支局没有下一级
      for (let i = 0; i < treeList.length; i += 1) {
        const val = treeList[i];
        // 支局和全部地区没有下一级
        val.level == '4' ? (val.isLeaf = true) : (val.isLeaf = false);
      }

      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            [payload.type == 'cascader' ? 'companiesCascaderList' : 'companiesTreeList']: treeList,
          },
        });
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        // message.error(msg);
      }
    },
    // 中邮获取右边列表数据
    *zyGetAcountsList({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(zyGetAcountsList, payload);
      if (!response) return;
      const { code, data, msg } = response;
      const { total, list, page, pageSize } = data;
      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            data: {
              list: isLegalData(list, []), // 防止后端传递空对象
              pagination: {
                total,
                pageSize,
                current: page,
                showQuickJumper: false,
                showSizeChanger: false,
              },
            },
          },
        });
        __dva_resolve(response);
      } else {
        __dva_reject();
        message.error(msg);
      }
    },
    // 中邮删除、切换状态
    *zySwitchStatus({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(zySwitchStatus, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success(msg);
        __dva_resolve(response);
      } else {
        __dva_reject();
        message.error(msg);
      }
    },
    // 中邮，添加及编辑账号
    *zySave({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(zySave, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success(msg);
        __dva_resolve(response);
      } else {
        __dva_reject();
        message.error(msg);
      }
    },
    // 中邮，账号权限分配
    *zyPrivilegeSet({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(zyPrivilegeSet, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success(msg);
        __dva_resolve(response);
      } else {
        __dva_reject();
        message.error(msg);
      }
    },
    // 中邮，添加支局
    *zyAddBranch({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(zyAddBranch, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success(msg);
        __dva_resolve(response);
      } else {
        __dva_reject();
        message.error(msg);
      }
    },
    // 中邮，编辑支局
    *zyEditBranch({ payload, __dva_resolve, __dva_reject }, { call }) {
      delete payload.branch_id;
      const response = yield call(zyEditBranch, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success(msg);
        __dva_resolve(response);
      } else {
        __dva_reject();
        message.error(msg);
      }
    },
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
